<?php
/**
 * User: Drery
 * Date: 2015/12/28
 * Time: 10:16
 */

namespace api\components;

use api\models\User;
use common\models\Level;
use common\models\ObjectLevel;
use yii\filters\AccessRule;
use yii\web\ServerErrorHttpException;


class LevelAccess extends AccessRule
{
    public function allows($action, $user, $request)
    {
        /** @var User $identity */
        $identity = $user->identity;

        $controller = $action->controller;
        if (!method_exists($controller, 'getCurrentDistrict')) {
            throw new ServerErrorHttpException();
        }

        $levelModel = $controller->getCurrentDistrict();
        if (!$levelModel)
            throw new ServerErrorHttpException();

        /** @var ObjectLevel $levelModel */
        if ($levelModel->level == Level::HIGHEST)
            return true;

        if (in_array($levelModel->relate_id, $identity->getValidDistrictIds()))
            return true;

        return false;
    }
}